package com.scaffold.springmvc.service;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wangjg.commons.dao.ResultMapping.ColumnInfo;

import com.scaffold.springmvc.dao.SqlDAO;
import com.scaffold.springmvc.dao.SqlDAO.ResultVo;

@Service
@Transactional(rollbackFor = Exception.class)
public class DbService {
	@Autowired
	private SqlDAO sqlDAO;
	
	public List<ColumnInfo> queryColumnInfo(String tableName) throws SQLException{
		return this.sqlDAO.queryColumnInfo(tableName);
	}
	
	public ResultVo exec(String sql) throws SQLException {
		if(isQuerySql(sql)){
			return this.query(sql);
		}else{
			return this.update(sql);
		}
	}
	
	public boolean isQuerySql(String sql){
		if(sql.startsWith("select") && Character.isWhitespace(sql.charAt(6))){
			return true;
		}
		return false;
	}
	
	public ResultVo query(String sql) throws SQLException{
		return this.sqlDAO.query(sql);
	}
	
	public ResultVo update(String sql) throws SQLException{
		int rowsNum = this.sqlDAO.update(sql);
		ResultVo result = new ResultVo();
		result.setRowsNum(rowsNum);
		return result;
	}

	public ResultVo getDatabaseMetaData(String...type) throws SQLException {
		return this.sqlDAO.getDatabaseMetaData(type);
	}
}